﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Serilog;
using System.IO;
using System.Runtime.CompilerServices;
using Serilog.Core;
using Serilog.Events;
namespace machine_registration.Helpers
{


    public static class LogExtensions
    {
        public static ILogger WithCallerInfo(this ILogger logger,
            [CallerFilePath] string filePath = "",
            [CallerLineNumber] int lineNumber = 0,
            [CallerMemberName] string memberName = "")
        {
            return logger
                .ForContext("CallerFile", Path.GetFileName(filePath))
                .ForContext("CallerLine", lineNumber)
                .ForContext("CallerMethod", memberName);
        }
    }

    public class CallerInfoEnricher : ILogEventEnricher
    {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var frame = new System.Diagnostics.StackTrace(true).GetFrame(6); // 根据调用堆栈深度调整 
            if (frame != null)
            {
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("CallerLine", frame.GetFileLineNumber()));
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("CallerMethod", frame.GetMethod()?.Name));
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("CallerFile", Path.GetFileName(frame.GetFileName())));
            }
        }
    }
}
